package com.vote.controllers;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.sql.Timestamp;
import java.util.List;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.ReqMapping;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import com.vote.annotation.LoginRequired;
import com.vote.annotation.TopListRequired;
import com.vote.model.Questionnaire;
import com.vote.model.User;
import com.vote.services.GroupService;
import com.vote.services.QuestionnaireService;
import com.vote.utils.HostHelper;
import com.vote.utils.JSONTransform;
import com.vote.utils.MsgHelper;

@LoginRequired
public class QmanagerController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(QmanagerController.class);
	
	@Autowired
	private QuestionnaireService questionnaireService;

	@Autowired
	private GroupService groupService;
	
	@TopListRequired
	@ReqMapping(path="/?$curpage:\\d*")
	public String index(Invocation inv, @Param("curpage")int curpage){
		User host = HostHelper.getHost(inv.getRequest());	
		int itemPerPage = 10;
		
		int qCount = questionnaireService.getUserQuestionnaireListCountByUserId(host.getUserId());
		List<Questionnaire> qList = questionnaireService.getUserQuestionnaireListByUserId(host.getUserId(), curpage * itemPerPage, itemPerPage);
		
		inv.addModel("qCount", qCount);
		inv.addModel("qList", qList);
		inv.addModel("curpage", curpage);
		inv.addModel("itemPerPage", itemPerPage);
		
		return "manager/manager_home";
	}
	
	@TopListRequired
	public String create(Invocation inv){
		User host = new User();
		
		return "manager/qedit";
	}
	
    public String createQuestionnaire(Invocation inv) {
    	User host = HostHelper.getHost(inv.getRequest());
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = inv.getRequest().getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) {
        	logger.error("create questionnaire get questionnaire json fail !!", e);
        	return "@fail";
        }

        JSONObject jsonObject = JSONObject.fromObject(jb.toString());
        Questionnaire questionnaire = JSONTransform.JSON2Model(jsonObject);

        questionnaire.setOwnerId(host.getUserId());

        questionnaire.setQuestionnaireTime(new Timestamp(System.currentTimeMillis()));
        try {
            questionnaireService.insertQuestionnaire(questionnaire);
        } catch (Exception e) {
            logger.error("create questionnaire insert questionnaire fail", e);
            return "@fail";
        }
    	return "@"+MsgHelper.rInfo((String)inv.getModel("HomeUrl")+"/qmanager/0", "问卷创建成功~~");
    }
    
    @ReqMapping(path="online/$qid:\\d+")
    public String online(Invocation inv, @Param("qid")int qid){
    	User host = HostHelper.getHost(inv.getRequest());
    	Questionnaire q = questionnaireService.getQuestionnaireById(qid);
    	if(host.getUserId() != q.getOwnerId()){
        	return "r:"+MsgHelper.rError((String)inv.getModel("HomeUrl")+"/qmanager/0", "小样，这不是你的问卷！！");
    	}
    	else{
	    	questionnaireService.onlineQuestionnaireById(qid);
	    	return "r:"+MsgHelper.rInfo((String)inv.getModel("HomeUrl")+"/qmanager/0", "问卷上线成功~~");
    	}
    }
    
    @ReqMapping(path="offline/$qid:\\d+")
    public String offline(Invocation inv, @Param("qid")int qid){
    	User host = HostHelper.getHost(inv.getRequest());
    	Questionnaire q = questionnaireService.getQuestionnaireById(qid);
    	if(host.getUserId() != q.getOwnerId()){
        	return "r:"+MsgHelper.rError((String)inv.getModel("HomeUrl")+"/qmanager/0", "小样，这不是你的问卷！！");
    	}
    	else{
	    	questionnaireService.offlineQuestionnaireById(qid);
	    	return "r:"+MsgHelper.rInfo((String)inv.getModel("HomeUrl")+"/qmanager/0", "问卷下线成功~~");
    	}
    }

    @ReqMapping(path="delete/$qid:\\d+")
    public String delete(Invocation inv, @Param("qid")int qid){
    	User host = HostHelper.getHost(inv.getRequest());
    	Questionnaire q = questionnaireService.getQuestionnaireById(qid);
    	if(host.getUserId() != q.getOwnerId()){
        	return "r:"+MsgHelper.rError((String)inv.getModel("HomeUrl")+"/qmanager/0", "小样，这不是你的问卷！！");
    	}
    	else{
	    	questionnaireService.deleteQuestionnaireById(qid);
	    	return "r:"+MsgHelper.rInfo((String)inv.getModel("HomeUrl")+"/qmanager/0", "删除问卷成功~~");
    	}
    }
    
    @ReqMapping(path="getgroup")
    public String getGroup(){
    	List<String> ls = groupService.getGroupList();
    	JSONArray ja = JSONArray.fromObject(ls);
    	return "@"+ja.toString();
    }
}
